package com.example.demo.untils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileCheckerNIO {

    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt"; // 替换为你的文件路径
        int maxRetries = 10;
        int retryDelayMs = 1000; // 1秒 = 1000毫秒

        boolean fileExists = checkFileExists(filePath, maxRetries, retryDelayMs);

        if (fileExists) {
            System.out.println("文件存在！");
        } else {
            System.out.println("文件不存在，已尝试 " + maxRetries + " 次。");
        }
    }

    /////////////
    public static boolean checkFileExists(String filePath, int maxRetries, int retryDelayMs) {
        Path path = Paths.get(filePath);
        int retryCount = 0;

        while (retryCount < maxRetries) {
            if (Files.exists(path)) {
                return true;
            } else {
                System.out.println("文件不存在，等待 " + retryDelayMs + " 毫秒后重试... (尝试 " + (retryCount + 1) + "/" + maxRetries + ")");
                try {
                    Thread.sleep(retryDelayMs);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.err.println("等待被中断！");
                    return false;
                }
                retryCount++;
            }
        }
        return false;
    }

     /// 文件夹不存在创建文件夹
     public static void  createDirectory(String  filePath){
        Path directoryPath = Paths.get(filePath);
        try {
            // 判断目录是否存在，如果不存在则创建，并且会创建多级目录结构
            if (Files.notExists(directoryPath)) {
                Files.createDirectories(directoryPath); // createDirectories()会创建多级目录，如果父目录不存在也会被创建
               // System.out.println("Directory created successfully!");
            } else {
              //  System.out.println("Directory already exists.");
            }
        } catch (IOException e) {
            System.err.println("Error creating directory: " + e.getMessage());
        }
    }
}